package comment_api

import (
	"fmt"
	"gin_study_blog/common"
	"gin_study_blog/common/http"
	"gin_study_blog/models"
	"gin_study_blog/service/redis"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func (CommentApi) CommentDeleteView(c *gin.Context) {
	var cr CommentDiggRequest
	err := c.ShouldBindUri(&cr)
	if err != nil {
		http.FailWithCode(http.ParamsError, c)
		return
	}

	var comment models.CommentModel
	err = common.DB.Take(&comment, cr.ID).Error
	if err != nil {
		http.FailWithMessage("评论不存在", c)
		return
	}
	// 统计评论下的子评论数, 再将自己加上
	subList := FindSubCommentCount(comment)
	count := len(subList) + 1
	redis.NewCommentCount().SetCount(comment.ArticleID, -count)
	// 判断是否是子评论
	if comment.ParentCommentID != nil {
		// 子评论
		// 找父评论, 减去对应的评论数
		common.DB.Model(&models.CommentModel{}).
			Where("id = ?", *comment.ParentCommentID).
			Update("comment_count", gorm.Expr("comment_count - ?", count))
	}

	// 删除子评论以及当前评论
	var deleteCommentIDList []uint
	for _, model := range subList {
		deleteCommentIDList = append(deleteCommentIDList, model.ID)
	}
	deleteCommentIDList = append(deleteCommentIDList, comment.ID)
	common.DB.Model(models.CommentModel{}).Delete("id in ?", deleteCommentIDList)

	http.IsOkWithMessage(fmt.Sprintf("共删除 %d 条评论", len(deleteCommentIDList)), c)
}
